﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
using Qy.Core;
using Qy.Scenario;
using Qy.Web.Authorize;
using Qy.Web.Authorize.Common;
using Qy.Web.Hubs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Qy.Web.Areas.Api;

[Route("Api/[controller]/[action]")]
[Verify]
public class NoticeController : Base
{
    private readonly ApplicationContext _applicationContext;
    private readonly NoticeKeyService _notice;
    private readonly ConfigService _configService;
    private readonly AttmentService _attment;
    private readonly UserService _user;
    private readonly MessageHub _messageHub;
    private readonly IHubContext<MessageHub> _onlineUserHubContext;
    public NoticeController(ApplicationContext applicationContext,
        UserService adminUserService,
        AttmentService attmentService,
        ConfigService configService,
        NoticeKeyService noticeKeyService,
        MessageHub messageHub
, IHubContext<MessageHub> onlineUserHubContext
        )
    {
        _applicationContext = applicationContext;
        _notice = noticeKeyService;
        _user = adminUserService;
        _configService = configService;
        _attment = attmentService;
        _messageHub = messageHub;
        _onlineUserHubContext = onlineUserHubContext;
    }

    [HttpGet]
    [ActionPermissionFilter(Permission = PermissionKeys.Notice_Index)]
    public async Task<IActionResult> IndexAsync([FromQuery] NoticeQuery query)
    {
        query.Uid = _applicationContext.ILoginUserInfoMethods.LoginUserId();
        PagedInfo<ViewNotice> list = await _notice.GetPageListAsync(query);
        return Success(new { data = list.Result, count = list.TotalNum });
    }

    [HttpGet, ActionName("Read")]
    [ActionPermissionFilter(Permission = PermissionKeys.Notice_Index)]
    public async Task<IActionResult> ReadAsync([FromQuery] int id)
    {
        if (id < 1) return Fail("ID错误！");
        int uid = _applicationContext.ILoginUserInfoMethods.LoginUserId();
        ViewNotice notice = await _notice.ReadAsync(id, uid);
        List<Attment> attments = null;
        if (!string.IsNullOrEmpty(notice.Att))
        {
            List<int> attIds = notice.Att.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToList();
            attments = await _attment.GetListAsync(attIds);
        }
        return Success(new { data = notice, attments });
    }
    [HttpGet, ActionName("RePly")]
    [ActionPermissionFilter(Permission = PermissionKeys.Notice_AddOrEdit)]
    public async Task<IActionResult> RePlyAsync([FromQuery] int uid)
    {
        return Success(new { data = await _user.GetCacheAsync(uid) });
    }
    [HttpGet]
    [ActionPermissionFilter(Permission = PermissionKeys.Notice_AddOrEdit)]
    public async Task<IActionResult> AddOrEditAsync()
    {
        var user = _applicationContext.ILoginUserInfoMethods.LoginUserId();
        //返回没有自己的用户列表
        return Success(new { userList = await _user.GetNameAsync(user) });
    }

    [HttpPost, ActionName("Create")]
   [ModelStateFilter]
    [ActionPermissionFilter(Permission = PermissionKeys.Notice_AddOrEdit)]
    [Log(Name = "发布信息")]
    public async Task<IActionResult> CreatePostAsync([FromBody] EditNotice editNotice)
    {
       bool res = await _notice.InsertByUid(editNotice, App.HttpContext.GetUId());
      if(res)
            return Success("发送信息，目标用户ID：" + editNotice.GetUid);
      else 
            return Fail("发送信息错误");
    }

    /// <summary>
    /// 发送通知公告表
    /// </summary>
    /// <returns></returns>
    [HttpGet]
    [ActionPermissionFilter(Permission = PermissionKeys.Notice_AddOrEdit)]
    public async Task<IActionResult> SendNoticeAsync(int noticeId = 0)
    {
        if (noticeId <= 0)
            return Fail("请求实体为空");
        ViewNotice response = await _notice.ReadOneAsync(noticeId);
        if (response != null)
            await _messageHub.Clients.All.SendAsync(HubsConstant.ReceiveNotice, response.Title, response.Content);
        return Success("发送成功！");
    }
    [HttpDelete]
    [ActionPermissionFilter(Permission = PermissionKeys.Notice_Delete)]
    [Log(Name = "删除消息")]
    public async Task<IActionResult> Delete(int id)
    {
        if (await _notice.DeleteAsync(id) > 0)
            return Success("删除消息 ID：" + id);
        else
            return Fail("删除失败 ID：" + id);
    }

}
